package com.fzq.orderserver.controller;

import com.fzq.client.ProductFeign;
import com.fzq.orderserver.converter.OrderForm2OrderDTOConverter;
import com.fzq.orderserver.dto.OrderDTO;
import com.fzq.orderserver.enums.ResultEnum;
import com.fzq.orderserver.exception.OrderException;
import com.fzq.orderserver.form.OrderForm;
import com.fzq.orderserver.service.OrderService;
import com.fzq.orderserver.utils.ResultVOUtil;
import com.fzq.orderserver.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private OrderService orderService;

    @GetMapping("/test")
    public ResponseEntity test() {
        return ResponseEntity.ok(productFeign.getProductList());
    }

    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new OrderException(ResultEnum.PARAM_REEOR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            throw new OrderException(ResultEnum.CART_EMPTTY);
        }

        OrderDTO result = orderService.create(orderDTO);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());
        return ResultVOUtil.success(map);
    }
}
